﻿using System.Collections.Generic;

namespace FortuneUniverse.Fortune.Dyson
{
  public class ProtoSet<T> : ProtoTable where T : Proto
  {
    public T[] dataArray;
    private Dictionary<int, int> dataIndices;

    public override void Init(int length) => this.dataArray = new T[length];

    public override Proto this[int index]
    {
      get => (Proto) this.dataArray[index];
      set => this.dataArray[index] = value as T;
    }

    public override int Length => this.dataArray.Length;

    public virtual void OnAfterDeserialize()
    {
      this.dataIndices = new Dictionary<int, int>();
      for (int index = 0; index < this.dataArray.Length; ++index)
      {
        this.dataArray[index].name = this.dataArray[index].Name;
        this.dataArray[index].sid = this.dataArray[index].SID;
        this.dataIndices[this.dataArray[index].ID] = index;
      }
    }

    public T Select(int id) => this.dataIndices.ContainsKey(id) ? this.dataArray[this.dataIndices[id]] : default (T);

    public bool Exist(int id) => this.dataIndices.ContainsKey(id);
  }
}
